// app/article/historyArticles.tsx
"use client"; // 标记为客户端组件

import { useState, useEffect } from 'react';
import HeaderAndNav from '../../components/HeaderAndNav'; // 使用现有的 HeaderAndNav 组件
import { fetchArticles, login } from '../../../app/api/api'; // 引入获取数据的方法
import Link from 'next/link'; // 导入 Link 组件

export default function HistoryArticlesPage() {
    const [articles, setArticles] = useState([]);
    const [error, setError] = useState(null);
    const [theme, setTheme] = useState('light'); // 默认主题

    useEffect(() => {
        // 从后端获取文章数据
        const fetchData = async () => {
            try {
                const token = await login(); // 登录获取 token
                const fetchedArticles = await fetchArticles(token); // 使用 token 获取文章
                setArticles(fetchedArticles);
            } catch (err) {
                console.error('Error fetching articles:', err);
                setError('无法加载文章数据，请稍后重试。');
            }
        };

        fetchData();
    }, []);

    return (
        <div className={`min-h-screen ${theme === 'dark' ? 'bg-black text-white' : 'bg-gray-100 text-black'}`}>
            {/* 使用现有的 HeaderAndNav 组件 */}
            <HeaderAndNav theme={theme} />

            <main className="p-8">
                <h2 className="text-3xl font-bold mb-8">历史文章</h2>

                {error ? (
                    <p className="text-center text-red-500">{error}</p>
                ) : (
                    <div className="space-y-6">
                        {articles.map((article) => {
                            const imageUrls = JSON.parse(article.imageUrls);
                            const backgroundImage = imageUrls.length > 0 ? imageUrls[0] : '/login7-1.jpg'; // 默认背景图片

                            return (
                                <Link href={`/article/${article.id}`} key={article.id} className="block">
                                    <div className="flex items-center space-x-4 p-4 rounded-lg shadow-md cursor-pointer transition-transform transform hover:scale-105 hover:shadow-lg">
                                        {/* 左侧显示背景图片 */}
                                        <div
                                            className="w-1/3 h-32 rounded-lg"
                                            style={{ backgroundImage: `url(${backgroundImage})`, backgroundSize: 'cover', backgroundPosition: 'center' }}
                                        ></div>

                                        {/* 右侧显示标题 */}
                                        <div className="w-2/3">
                                            <h3 className="text-xl font-bold mb-2">{article.title}</h3>
                                        </div>
                                    </div>
                                </Link>
                            );
                        })}
                    </div>
                )}
            </main>
        </div>
    );
}
